﻿package capricornus.utils.soundWave
{
	//引入相关的类
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundMixer;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;

	//自定义wave类，实现相关操作
	public class SoundWave extends Sprite {
		//定义所需变量
		private var sound:Sound;
		private var ba:ByteArray;
		private var num:Number;
		private var sound_channel:SoundChannel;
		private var t:Number = 0;

		//类的构造函数，播放声音文件，并侦听ENTER_FRAME事件
		public function SoundWave() {
			sound = new Sound();
			ba = new ByteArray();
			sound.load(new URLRequest("test.mp3"));
			sound_channel = sound.play();
			//添加事件侦听，用spectrum函数处理
			this.addEventListener(Event.ENTER_FRAME, spectrum);
		}

		//绘制波形主函数
		private function drawFunction(thickness:Number, color:Number):void {
			graphics.lineStyle(thickness, color, 100);
			//获取当前声音频谱信息
			SoundMixer.computeSpectrum(ba, false, 0);
			//绘制声波曲线
			for (var i:int = 30; i <= stage.stageWidth - 30; i++) {
				//以浮点形式读出当前声音频谱信息
				num = ba.readFloat() * 360;
				if (i>30) {
					var fi:Number = stage.stageHeight / 2 + num;
					graphics.lineTo(i, fi);
				} else {
					graphics.moveTo(30, stage.stageHeight / 2 + num);
				}
			}
		}
		//侦听处理函数，调用绘制波形函数
		private function spectrum(event:Event):void {
			graphics.clear();
			drawFunction(1, 0xbb00aa);
		}
	}
}